package com.logjun.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.logjun.reggie.common.BaseContext;
import com.logjun.reggie.common.CustomException;
import com.logjun.reggie.entity.*;
import com.logjun.reggie.mapper.OrderMapper;
import com.logjun.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {


    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    AddressBookService addressBookService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    UserService userService;

    /**
     * 用户下单
     * @param orders
     */
    @Transactional
    public void submit(Orders orders) {
        //获取当前用户id
        Long userId = BaseContext.getCurrentId();
        //用时间戳生成订单号
        Long orderId = System.currentTimeMillis();
        //订单总金额
        AtomicInteger amount = new AtomicInteger(0);
        //根据id查购物车数据，将购物车添加到订单明细表中
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
        //判断购物车数据是否为空
        if (null == list || list.size() == 0) {
            throw new CustomException("购物车数据为空");
        }
        //判断是否存在地址信息
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (null == addressBook){
            throw new CustomException("请先设置或选择一个地址");
        }
        //将购物车中的数据赋给订单明细
        List<OrderDetail> orderDetails = list.stream().map(item -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            if (null != item.getDishId()){
                orderDetail.setDishId(item.getDishId());
            }else {
                orderDetail.setSetmealId(item.getSetmealId());
            }
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        //获取用户信息，得到用户名字
        User user = userService.getById(userId);
        //添加订单数据
        orders.setId(orderId);
        orders.setAddress(addressBook.getDetail());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        //添加订单
        this.save(orders);
        //添加订单明细
        orderDetailService.saveBatch(orderDetails);
        //删除购物车
        shoppingCartService.remove(queryWrapper);
    }
}